package com.axend.aerosense.dev.fragment;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.widget.NestedScrollView;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.axend.aerosense.common.UrlApi;
import com.axend.aerosense.common.bean.RadarType;
import com.axend.aerosense.common.bean.UnassignedRadar;
import com.axend.aerosense.common.databinding.CommonLayoutBottomDialogBinding;
import com.axend.aerosense.common.databinding.CommonLayoutTopDialogBinding;
import com.axend.aerosense.common.ui.CommonPopupWindow;
import com.axend.aerosense.common.ui.CustomTipsDialog;
import com.axend.aerosense.common.util.ClickUtils;
import com.axend.aerosense.dev.activity.DevBindRoomActivity;
import com.axend.aerosense.dev.adapter.DevDeviceListAdapter;
import com.axend.aerosense.common.bean.BindRoomBean;
import com.axend.aerosense.common.bean.MoveBindRoomBean;
import com.axend.aerosense.common.bean.GetRadarList;
import com.axend.aerosense.dev.viewmodel.RadarsViewModel;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.gyf.immersionbar.ImmersionBar;
import com.axend.aerosense.base.fragment.MvvmBaseFragment;
import com.axend.aerosense.base.impl.ILoadDataResult;
import com.axend.aerosense.base.impl.ILoginStatusChanged;
import com.axend.aerosense.base.impl.IOperationResult;
import com.axend.aerosense.base.livedatabus.LiveDatabus;
import com.axend.aerosense.base.viewmodel.BaseViewModelFactroy;
import com.axend.aerosense.common.base.IPageView;
import com.axend.aerosense.common.bean.RadarBean;
import com.axend.aerosense.common.config.Gobal;
import com.axend.aerosense.common.router.RouterActivityPath;
import com.axend.aerosense.common.router.RouterFragmentPath;
import com.axend.aerosense.dev.R;
import com.axend.aerosense.dev.databinding.DevFragmentMainBinding;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Route(path = RouterFragmentPath.Dev.PAGE_MAIN_DEV)
public class DevicesMainFragment extends MvvmBaseFragment<DevFragmentMainBinding, RadarsViewModel>
        implements ILoginStatusChanged, ILoadDataResult<GetRadarList> {

    private List<RadarBean> list = new ArrayList<>();
    private DevDeviceListAdapter deviceListAdapter;
    private boolean isSelectAll = false;  //是否全选
    private CommonPopupWindow bottomWindow, topWindow;

    private boolean isCreatView = false;

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        ((AppCompatActivity) getActivity()).setSupportActionBar(viewDataBinding.devToolbar);
//        int statusBarHeight = getStatusBarHeight();
//        viewDataBinding.devContentParent.setPadding(0,statusBarHeight,0,0);
        initView();
    }

    private void initView() {
        viewDataBinding.devConstraintLayoutAdd.setOnClickListener(v->{
            if (ClickUtils.isFastClick()) return;
            ARouter.getInstance()
                    .build(RouterActivityPath.Dev.PAGE_DEV_HOME)
                    .navigation();
        });
        viewDataBinding.devIvAdd.setOnClickListener(v -> {
            if (ClickUtils.isFastClick()) return;
            ARouter.getInstance()
                    .build(RouterActivityPath.Dev.PAGE_DEV_HOME)
                    .navigation();
        });

        deviceListAdapter = new DevDeviceListAdapter(list);
        viewDataBinding.devDeviceList.setLayoutManager(new GridLayoutManager(getContext(),2));
        viewDataBinding.devDeviceList.setAdapter(deviceListAdapter);
        //item点击事件
        deviceListAdapter.setOnItemClickListener((item, position) -> ARouter.getInstance()
                .build(RouterActivityPath.Dev.PAGE_DEV_HOME)
                .withSerializable("radarBean", item)
                .navigation());
        //item长按事件
        deviceListAdapter.setOnItemLongClickListener((item, position) -> {
            if(null != bottomWindow && bottomWindow.getContentView().isShown()){
                return true;
            }
            showPopupWindow();
            //管理设备时禁止刷新，否则会出bug
            viewDataBinding.devRefreshLayout.setEnableRefresh(false);
            return true;
        });

        viewDataBinding.devNestedScrollView.setOnScrollChangeListener((NestedScrollView.OnScrollChangeListener) (v, scrollX, scrollY, oldScrollX, oldScrollY) -> {
            Rect scrollBounds = new Rect();
            viewDataBinding.devDeviceList
                    .getChildAt(0)
                    .getGlobalVisibleRect(scrollBounds);

            Rect toolbarRect = new Rect();
            viewDataBinding.devToolbar.getGlobalVisibleRect(toolbarRect);

            if (scrollBounds.top > toolbarRect.bottom){
                viewDataBinding.devToolbar.setBackgroundResource(android.R.color.transparent);
//                isImmersionBarTransparent = true;
//                setImmersionBar();
//                viewDataBinding.devTvRoomName.setTextColor(getResources().getColor(R.color.white));
//                viewDataBinding.devIvAdd.setImageResource(R.drawable.common_user_icon_add);
            }else {
                viewDataBinding.devToolbar.setBackgroundResource(R.color.common_setting_item_bg);
//                isImmersionBarTransparent = false;
//                setImmersionBar();
//                viewDataBinding.devTvRoomName.setTextColor(getResources().getColor(R.color.black));
//                viewDataBinding.devIvAdd.setImageResource(R.drawable.common_user_icon_add2);
            }
        });
        viewDataBinding.devTvRoomName.setTextColor(getResources().getColor(R.color.black));
        viewDataBinding.devIvAdd.setImageResource(R.drawable.common_user_icon_add2);

        viewDataBinding.devRefreshLayout.setOnRefreshListener(v->{
            if(null != viewModel){
                viewModel.onLoad();
            }
        });
        viewDataBinding.devRefreshLayout.setEnableLoadMoreWhenContentNotFull(false);
        viewDataBinding.devRefreshLayout.setNoMoreData(true);
        setLoadSir(viewDataBinding.devRefreshLayout);
        showLoading();
        viewModel.onLoad();
        LiveDatabus.getInstance().with(Gobal.EVENT_KEY.DEV_COUNT_CHANGE ,Integer.class)
                .observe(getViewLifecycleOwner(), bean-> {
                    if(isCreatView){
                        viewModel.onLoad();
                    }
                });
//        LiveDatabus.getInstance().with(Gobal.EVENT_KEY.REFESH_ROOM, Integer.class).observe(getViewLifecycleOwner(), integer -> {
//            onRetryBtnClick();
//        });

        isCreatView = true;

        LogUtils.d("当前服务器IP： " + UrlApi.getBaseUrl());
    }

    public void setImmersionBar() {
//        if(isImmersionBarTransparent) {
//            ImmersionBar.with(this)
//                    .statusBarColor(R.color.common_setting_item_bg)
//                    .fitsSystemWindows(true)
//                    .statusBarDarkFont(true)
//                    .autoDarkModeEnable(true).init();
//        }else{
//            ImmersionBar.with(this)
//                    .statusBarColor(android.R.color.white)
//                    .fitsSystemWindows(true)
//                    .statusBarDarkFont(true)
//                    .autoDarkModeEnable(true).init();
//        }
        ImmersionBar.with(this)
                .statusBarColor(R.color.common_setting_item_bg)
                .fitsSystemWindows(true)
                .statusBarDarkFont(true)
                .autoDarkModeEnable(true).init();
    }

    private void showPopupWindow(){
        deviceListAdapter.setEnableClick(false);
        //显示复选框
        deviceListAdapter.setCheckBoxVisibility(true);

        bottomWindow = new CommonPopupWindow<CommonLayoutBottomDialogBinding>(
                getActivity(),
                R.layout.common_layout_bottom_dialog) {

                @Override
                protected void initEvent(CommonLayoutBottomDialogBinding bottomBinding) {
                    //移动
                    bottomBinding.moving.setOnClickListener(v -> {
                        Map<Integer, RadarBean> checkedItems = deviceListAdapter.getCheckedItems();
                        if (null != checkedItems && checkedItems.size() > 0){
                            if (!checkRadarType(checkedItems)){
                                showMoveTips();
                                return;
                            }
                            Intent intent = new Intent(getActivity(), DevBindRoomActivity.class);
                            startActivityForResult(intent, DevBindRoomActivity.BING_REQUEST_CODE);
                        }else {
                            ToastUtils.showShort(R.string.dev_move_tips);
                        }
                    });
                    //删除
                    bottomBinding.delete.setOnClickListener(v->{
                        viewDataBinding.devRefreshLayout.setEnableRefresh(true);
                        List<String> radarUuid = new ArrayList<>();
                        Map<Integer, RadarBean> checkedItems = deviceListAdapter.getCheckedItems();
                        if(null == checkedItems || checkedItems.size() == 0){
                            ToastUtils.showShort(R.string.dev_del_tips);
                            return;
                        }else{
                            Iterator<Integer> it = checkedItems.keySet().iterator();
                            while(it.hasNext()){
                                Integer key = it.next();
                                radarUuid.add(checkedItems.get(key).getRadarUuid());
                            }
                        }
                        MoveBindRoomBean bean = new MoveBindRoomBean(radarUuid, "");
                        viewModel.deleteRadars(getActivity(), bean, new IOperationResult() {
                            @Override
                            public void onSuccess() {
                                closePopupWindow();
                                Activity activity = getActivity();
                                if(activity instanceof IPageView){
                                    ((IPageView)activity).setViewPageScolleEnabled(true);
                                }
                                deviceListAdapter.getCheckedItems().clear();
    //                          deviceListAdapter.deleteItem();
                                viewModel.onLoad();
                                LiveDatabus.getInstance().with(Gobal.EVENT_KEY.REFESH_ROOM, Integer.class).postValue(1);
                            }

                            @Override
                            public void onFail() {
                                closePopupWindow();
                            }
                        });
                    });
                }
        };
        bottomWindow.showAtLocation(viewDataBinding.devRefreshLayout, Gravity.BOTTOM, 0, 0);

        topWindow = new CommonPopupWindow<CommonLayoutTopDialogBinding>(
                getActivity(),
                R.layout.common_layout_top_dialog) {

                @Override
                protected void initEvent(CommonLayoutTopDialogBinding topBinding) {
                    //全选\全不选
                    topBinding.selectAll.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //全选
                            if (isSelectAll){
                                deviceListAdapter.setSelectAll(false);
                                topBinding.selectAll.setText(R.string.dev_select_all);
                                isSelectAll = false;
                            }else {
                                deviceListAdapter.setSelectAll(true);
                                topBinding.selectAll.setText(R.string.dev_unselect_all);
                                isSelectAll = true;
                            }
                        }
                    });
                    //取消按钮
                    topBinding.cancel.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            closePopupWindow();
                            Activity activity = getActivity();
                            if(activity instanceof IPageView){
                                ((IPageView)activity).setViewPageScolleEnabled(true);
                            }
                            deviceListAdapter.setEnableClick(true);
                            //隐藏复选框
                            deviceListAdapter.setCheckBoxVisibility(false);
                            //取消全选
                            deviceListAdapter.setSelectAll(false);
                            viewDataBinding.devRefreshLayout.setEnableRefresh(true);
                        }
                    });
                    //已选中
                    topBinding.selected.setText(String.format(getString(R.string.dev_selected), "0"));
                    deviceListAdapter.setOnItemCountChangeListener(checkedItems -> {
                        int count = checkedItems.size();
                        topBinding.selected.setText(String.format(getString(R.string.dev_selected),  count + ""));
                        //当手动全部选中后，改变上面左边文字
                        if (count == deviceListAdapter.getItemCount()){
                            topBinding.selectAll.setText(R.string.dev_unselect_all);
                            isSelectAll = true;
                        }else {
                            topBinding.selectAll.setText(R.string.dev_select_all);
                            isSelectAll = false;
                        }
                    });
                }
        };
        int position[] = new int[2];
        viewDataBinding.devDeviceList.getLocationOnScreen(position);
        try{
            if(position[1] > 0){
                topWindow.getPopupWindow().setHeight(position[1]);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        topWindow.getPopupWindow().setClippingEnabled(false);

        topWindow.showAtLocation(viewDataBinding.devRefreshLayout, Gravity.TOP, 0, 0);
        Activity activity = getActivity();
        if(activity instanceof IPageView){
            ((IPageView)activity).setViewPageScolleEnabled(false);
        }
    }

    private void closePopupWindow(){
        if(null != bottomWindow){
            bottomWindow.dismiss();
            bottomWindow = null;
        }
        if(null != topWindow){
            topWindow.dismiss();
            bottomWindow = null;
        }
    }

    //显示移动设备提示
    private void showMoveTips(){
        CustomTipsDialog tipsDialog = new CustomTipsDialog(getContext(), getString(R.string.common_move_tips));
        tipsDialog.setOnClickBottomListener(new CustomTipsDialog.OnClickBottomListener() {
            @Override
            public void onPositiveClick() {
                tipsDialog.dismiss();
            }

            @Override
            public void onNegtiveClick() {
                tipsDialog.dismiss();
            }
        });
        tipsDialog.show();
    }

    /**
     * 检查移动的雷达，如果雷达个数大于3，返回false
     * 每个房间assure和wavve雷达都不能超过一台，否则返回false
     * @param map
     * @return
     */
    private boolean checkRadarType(Map<Integer, RadarBean> map){
        if (map.size() > 2) return false;

        int assureCount = 0;
        int wavveCount = 0;
        for (RadarBean r : map.values()){
            if (r.getType() == RadarType.ASSURE){
                assureCount++;
            }else {
                wavveCount++;
            }
            if (assureCount > 1 || wavveCount > 1){
                return false;
            }
        }
        return true;
    }

    //设置顶部未分配雷达提示信息
    private void setTopUnassignedTips(int radarCount){
        viewDataBinding.devTopTips.setVisibility(radarCount > 0 ? View.VISIBLE : View.GONE);
        String str = String.format(getString(R.string.room_unassigned_devices_list_tips), String.valueOf(radarCount));
        viewDataBinding.devTopTips.setText(str);
    }

    @Override
    public void onResume() {
        super.onResume();
        setImmersionBar();

    }

//    @Override
//    public void onResume() {
//        super.onResume();
//        ImmersionBar.with(this)
//                .statusBarColor(R.color.colorAccent)
//                .fitsSystemWindows(true)
//                .statusBarDarkFont(true)
//                .autoDarkModeEnable(true).init();
//    }

    @Override
    public int getLayoutId() {
        return R.layout.dev_fragment_main;
    }

    @Override
    public int getBindingVariable() {
        return 0;
    }

    @Override
    protected RadarsViewModel getViewModel() {
        BaseViewModelFactroy<GetRadarList> myViewModelFactroy = new BaseViewModelFactroy<>(this, this);
        RadarsViewModel tmp = new ViewModelProvider(this, myViewModelFactroy).get(RadarsViewModel.class);
        return tmp;
    }

    @Override
    protected void onRetryBtnClick() {
        showLoading();
        viewModel.onLoad();
    }

    @Override
    public void loginStatusChanged() {
        if(isCreatView){
            getViewModel().isRefresh = false;
            onRetryBtnClick();
        }
    }

    @Override
    public void loadDataSuccess(GetRadarList radarList) {

        viewDataBinding.devRefreshLayout.finishRefresh();
        deviceListAdapter.getCheckedItems().clear();
        if(null != radarList && radarList.getRadarInfo() != null ){
            deviceListAdapter.setEnableClick(true);
            deviceListAdapter.setCheckBoxVisibility(false);

            list.clear();
            list.addAll(radarList.getRadarInfo());
            deviceListAdapter.upDateList(setRadarType(radarList.getRadarInfo(), radarList.getUnassignedRadar()));
            if(radarList.getUnassignedRadar() != null
                    && radarList.getUnassignedRadar().size() > 0
                    && radarList.getUnassignedRadar().get(0) != null){
                setTopUnassignedTips(radarList.getUnassignedRadar().size());
            }else {
                setTopUnassignedTips(0);
            }
            if(list.size() > 0){
                viewDataBinding.devConstraintLayoutAdd.setVisibility(View.GONE);
                return;
            }
        }
        viewDataBinding.devConstraintLayoutAdd.setVisibility(View.VISIBLE);

    }

    @Override
    public void loadDataFail(String decs) {
        viewDataBinding.devRefreshLayout.finishRefresh();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if(DevBindRoomActivity.BING_REQUEST_CODE == requestCode && null != data){
            viewDataBinding.devRefreshLayout.setEnableRefresh(true);

            BindRoomBean bindRoomBean = (BindRoomBean) data.getSerializableExtra("ROOM");
            if(null == bindRoomBean){
                return;
            }

            deviceListAdapter.setEnableClick(true);
            deviceListAdapter.setCheckBoxVisibility(false);

            List<RadarBean> radarBeans = new ArrayList<>();
            Map<Integer, RadarBean> checkedItems = deviceListAdapter.getCheckedItems();
            if(null == checkedItems || checkedItems.size() == 0){
                ToastUtils.showShort(R.string.dev_move_tips);
                return;
            }else{
                Iterator<Integer> it = checkedItems.keySet().iterator();
                while(it.hasNext()){
                    Integer key = it.next();
                    radarBeans.add(checkedItems.get(key));
                }
            }

            MoveBindRoomBean bean = new MoveBindRoomBean(bindRoomBean.getRoomUuid(), radarBeans);
            viewModel.devsBindRoom(getActivity(), bean, new IOperationResult() {
                @Override
                public void onSuccess() {
                    closePopupWindow();
                    Activity activity = getActivity();
                    if(activity instanceof IPageView){
                        ((IPageView)activity).setViewPageScolleEnabled(true);
                    }
                    deviceListAdapter.getCheckedItems().clear();
//                    deviceListAdapter.deleteItem();
                    LiveDatabus.getInstance().with(Gobal.EVENT_KEY.REFESH_ROOM, Integer.class).postValue(1);
                    onRetryBtnClick();
                }

                @Override
                public void onFail() {
                    closePopupWindow();
                }
            });
            return;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private List<RadarBean> setRadarType(List<RadarBean> radarBeanList, ArrayList<UnassignedRadar> unassignedRadar){
        if (radarBeanList != null && unassignedRadar != null){
            for (UnassignedRadar radar : unassignedRadar) {
                for (RadarBean bean : radarBeanList){
                    if (null == radar || null == bean) continue;

                    if (radar.getRadarUuid().equals(bean.getRadarUuid())){
                        bean.setUnassigned(true);
                        break;
                    }
                }
            }
        }
        return radarBeanList;
    }
}